<?php
namespace Anchu\Zhelb\Login;

class ZhelbLegalLogin
{
    private $url;
    private $access_key;
    private $secret_key;

    /**
     * ZhelbLegalLogin constructor.
     * @param $url : 浙里办的接口，如：https://ibcdsg.zj.gov.cn:8443/.../user/query
     * @param $access_key : 在irs平台上发起对接申请通过后获取到的ak
     * @param $secret_key : 在irs平台上发起对接申请通过后获取到的sk
     */
    public function __construct($url, $access_key, $secret_key)
    {
        $this->url = $url;
        $this->access_key = $access_key;
        $this->secret_key = $secret_key;
    }

    /**
     * 在测试环境上，返回TOKEN_NOT_EXIST表示已经调通
     * @param $ssotoken :  浙里办法人--验证令牌
     * @return {"success":false,"code":"TOKEN_NOT_EXIST","msg":"Token不存在","errCode":1410025,"info":null}
     */
    public function getZhelbUserInfo($ssotoken) {
        return $this->curl($ssotoken);
    }

    /**
     * 请求头的时间戳，时区为GMT+8，格式为：Tue, 09 Nov 2021 08:49:20 GMT。
     * API服务端允许客户端请求最大时间误差为100秒。
     */
    private function getHeaderDateTimeByGMT()
    {
        return gmdate("D, d M Y H:i:s") . " GMT";
    }

    /**
     * 将http的query进行ASCII排序
     * @param string $httpQuery
     * @return string
     */
    private function getKsortQuery($httpQuery = '')
    {
        if (empty($httpQuery)) {
            return '';
        }
        $list = explode('&', $httpQuery);
        if (empty($list)) {
            return http_build_query([]);
        }
        $finalList = [];
        foreach ($list as $v) {
            $itemList = explode('=', $v);
            $key = $itemList[0] ?? '';
            $value = $itemList[1] ?? '';
            $finalList[$key] = $value;
        }
        ksort($finalList);
        return http_build_query($finalList);
    }

    // 请求头的获取签名
    private function getHeaderSignature($url, $httpMethod = 'POST', $time = '')
    {
        $urlList = parse_url($url);
        $urlList = !empty($urlList) ? $urlList : [];
        $httpUri = $urlList['path'] ?? '';
        $httpQuery = $urlList['query'] ?? '';
        $queryStream = $this->getKsortQuery($httpQuery);
        $ak = $this->access_key;
        $sk = $this->secret_key;
        $n = "\n";
        $signString = $httpMethod . $n
            . $httpUri . $n
            . $queryStream . $n
            . $ak . $n
            . $time . $n;
        $sign = base64_encode(hash_hmac('sha256', $signString, $sk, true));
        return $sign;
    }


    private function curl($token)
    {
        try {
            $time = $this->getHeaderDateTimeByGMT();
            $head = [
                'Content-Type:application/json',
                'X-BG-HMAC-SIGNATURE:' . $this->getHeaderSignature($this->url, 'POST', $time),
                'X-BG-HMAC-ALGORITHM:hmac-sha256',
                'X-BG-HMAC-ACCESS-KEY:' . $this->access_key,
                'X-BG-DATE-TIME:' . $time
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['token' => $token]));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
            // 取消结果自动打印
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $res = curl_exec($ch);
            curl_close($ch);

            return $res;
        } catch (\Exception $e) {
            exit($e->getMessage());
        }

    }
}